<template>
  <div>
    <a-card class="card">
      <template slot="title" >
        <span style="display:flex;align-items: center;">
          综合报表
          <a-tooltip style="margin-left:6px;">
            <template slot="title">
              综合报表
            </template>
            <a-icon style="cursor: pointer;" type="exclamation-circle" :style="{ fontSize: '12px',color:'#888888' }"/>
          </a-tooltip>
        </span>
      </template>
      <div style="display: flex;align-items: center;">
        <!-- <a-upload
          name="file"
          action="#"
          :beforeUpload="beforeUpload"
        >
          <a-button> <a-icon type="upload" /> 导入 </a-button>
        </a-upload> -->
        <a-button a-button type="primary" @click="createData">生成数据</a-button>
        <a-button a-button type="primary" @click="handle_export" style="margin-left:10px;">导出</a-button>
        <span style="margin-left: 15px;">月工作日</span>
        <a-input v-model="days" placeholder="输入月工作日" style="width:50px;margin-left: 5px;"/>
        <span style="margin-left: 15px;">周工作日</span>
        <a-input v-model="weekDays" placeholder="周工作日数量" style="width:50px;margin-left: 5px;"/>
        <span style="margin-left: 15px;">当前工作日</span>
        <a-input v-model="workDay" placeholder="当前第几个工作日" style="width:50px;margin-left: 5px;"/>
        <span style="margin-left: 15px;">昨日时间</span>
        <a-date-picker
          :allowClear="false"
          :defaultValue="moment().startOf('day').add(-1, 'days')"
          :disabled-date="disabledDate" @change="formDateChange" style="width:140px;margin-left: 5px;" />
        <span style="margin-left: 15px;">
          自定义时间
          <a-tooltip placement="topLeft" style="cursor: pointer;" arrow-point-at-center>
            <template slot="title">
              <span >列表展示本时间段内的数据</span>
            </template>
            <a-icon style="cursor: pointer;" type="exclamation-circle" :style="{ fontSize: '12px',color:'#888888' }"/>
          </a-tooltip>
        </span>
        <a-range-picker
        :defaultValue="[moment().startOf('month'), moment().startOf('day')]"
        :ranges="{ '昨天': [moment().add(-1, 'days'), moment().add(-1, 'days')], '过去7天': [moment().add(-7, 'days'), moment().add(-1, 'days')], 
                  '过去30天': [moment().add(-30, 'days'), moment().add(-1, 'days')], '本月': [moment().startOf('month'), moment().endOf('month')],'上月': [moment(moment().month(moment().month() - 1).startOf('month').valueOf()), moment(moment().month(moment().month() - 1).endOf('month').valueOf())] }"
        :disabled-date="disabledDate2" @change="formDateChange2" style="width:240px;margin-left: 5px;" 
      />
      </div>
      <a-table id="shumeiTable" rowKey="name" :columns="columns" :data-source="dayList" :scroll="{x:1200}" style="margin-top: 20px" :loading="loading">
        <div slot="dayRenwu" slot-scope="record">
          {{(record).toFixed(2)}}
        </div>
        <div slot="yesterdaySuccess" slot-scope="record">
          {{(record*100).toFixed(2) + '%'}}
        </div>
        <div slot="weekSuccess" slot-scope="record">
          {{(record*100).toFixed(2) + '%'}}
        </div>
        <div slot="monthSuccess" slot-scope="record">
          {{(record*100).toFixed(2) + '%'}}
        </div>
        <div slot="todaySuccess" slot-scope="record">
          {{(record*100).toFixed(2) + '%'}}
        </div>
        <div slot="yujiJindu" slot-scope="record">
          {{(record*100).toFixed(2) + '%'}}
        </div>
        <div slot="weekRenwu" slot-scope="record">
          {{(record).toFixed(2)}}
        </div>
        <div slot="yujiPrice" slot-scope="record">
          {{(record).toFixed(2)}}
        </div>
      </a-table>
    </a-card>  
  </div>
</template>

<script>
import xlsx from 'xlsx';
import moment from 'moment';
import FileSaver from 'file-saver';
import {getDataList} from '@/api/shumei/shumei'

const columns = [
  {
    title: '姓名',
    width: 100,
    dataIndex: 'name'
  },
  {
    title: '今日制作数',
    width: 120,
    dataIndex: 'todayNum',
  },
  {
    title: '今日业绩',
    width: 100,
    dataIndex: 'todayPrice',
  },
  {
    title: '每日任务',
    width: 100,
    dataIndex: 'dayRenwu',
    scopedSlots: { customRender: 'dayRenwu' },
  },
  {
    title: '今日达成率',
    width: 120,
    dataIndex: 'todaySuccess',
    scopedSlots: { customRender: 'todaySuccess' },
  },
  {
    title: '昨日制作数量',
    width: 150,
    dataIndex: 'yesterdayNum',
  },
  {
    title: '昨日业绩',
    width: 150,
    dataIndex: 'yesterdayPrice',
  },
  {
    title: '昨日达成率',
    width: 120,
    dataIndex: 'yesterdaySuccess',
    scopedSlots: { customRender: 'yesterdaySuccess' },
  },
  {
    title: '本周制作数',
    width: 120,
    dataIndex: 'weekNum',
  },
  {
    title: '本周业绩',
    width: 100,
    dataIndex: 'weekPrice',
  },
  {
    title: '本周任务',
    width: 100,
    dataIndex: 'weekRenwu',
    scopedSlots: { customRender: 'weekRenwu' },
  },
  {
    title: '本周达成',
    width: 100,
    dataIndex: 'weekSuccess',
    scopedSlots: { customRender: 'weekSuccess' },
  },
  {
    title: '本月当前制作数',
    width: 100,
    dataIndex: 'monthNum',
  },
  {
    title: '本月当前业绩',
    width: 100,
    dataIndex: 'monthPrice',
  },
  {
    title: '月度总任务',
    width: 120,
    dataIndex: 'monthTotalPrice',
  },
  {
    title: '月度达成',
    width: 100,
    dataIndex: 'monthSuccess',
    scopedSlots: { customRender: 'monthSuccess' },
  },
  {
    title: '预计达成金额',
    width: 100,
    dataIndex: 'yujiPrice',
    scopedSlots: { customRender: 'yujiPrice' },
  },
  {
    title: '预计月度达成',
    width: 100,
    dataIndex: 'yujiJindu',
    scopedSlots: { customRender: 'yujiJindu' },
  },
  
]

export default {
  data() {
    return {
      data:[],  //Excel中的data
      moment,
      days:22, // 本月天数
      weekDays:5, // 本周工作日数量
      workDay: 4,  // 当前第几个工作日
      dayList:[], // 今日数据，用于生成报表
      columns,
      loading:false,
      YesterdayDate: moment().subtract(1, 'days').startOf('day').format('x'),
      start_date: moment().startOf('month').format('YYYY-MM-DD'),
      end_date: moment().startOf('day').format('YYYY-MM-DD'),
    }
  },
  created(){
    this.init()
    this.createData()
  },
  methods:{
    init(){
      this.workDay = this.workday_count(moment().startOf('month'), moment().add(1, 'days').startOf('day'))
      this.days = this.workday_count(moment().startOf('month'), moment().endOf('month'))
    },
    createData(){
      this.loading = true
      let params = {
        end_date: this.end_date,
        start_date: this.start_date,
      }
      getDataList(params).then((res) => { 
        if(res.errcode == 0){
          for(let item of res.data){
            item['num'] = item['quantity']
            item['totalPrice'] = item['monthTarget']
          }
          this.data = res.data
          this.getDayList()
        }
      }).catch(()=>{
        this.loading = false
      });
    },
    workday_count(start, end) {
      //获取当前是第几个工作日
      let count = 0;
      let current = start;
      while (current< end) {
        const day = current.day();
        if (day > 0 && day < 6) {
          count += 1;
        }
        current = current.add(1, 'd');
      }
      return count;
    },
    getDayList(){
      this.dayList = []
      let data = this.data
      for(let item of data){
        // console.log(item, item['name'])
        let f = this.dayList.find(e=>e.name == item.name)
        if(!f){
          // 找到改name下totalPrice的最小值
          let totalPrice
          data.forEach(e=>{
            if(!totalPrice){totalPrice = item.totalPrice}
            if(e.name == item.name && totalPrice > e.totalPrice){
              totalPrice = e.totalPrice
            }
          })

          this.dayList.push({
            name: item.name, // 姓名
            todayNum: this.getTodayNum(data, item), // 今日制作数量
            todayPrice: this.getTodayPrice(data, item), // 今日业绩
            todaySuccess: this.getTodayPrice(data, item) / this.getDayRenwu(data, item), // 今日达成率， 今日业绩 / 今日任务
            yesterdayNum: this.getYesterdayNum(data, item), //昨日制作数量
            yesterdayPrice: this.getYesterdayPrice(data, item),  // 昨日业绩
            dayRenwu: this.getDayRenwu(data, item), //每日任务
            yesterdaySuccess: this.getYesterdayPrice(data, item) / this.getDayRenwu(data, item), // 昨日达成率， 昨日业绩 / 每日任务
            weekNum: this.getWeekNum(data, item), // 本周制作数
            weekPrice: this.getWeekPrice(data, item),  //本周业绩
            weekRenwu: this.getDayRenwu(data, item) * this.weekDays, // 本周任务 = 每日任务 * 周工作日
            weekSuccess: this.getWeekPrice(data, item) / (this.getDayRenwu(data, item) * this.weekDays), // 本周达成 = 本周业绩 / 本周任务
            monthNum: this.getMonthNum(data, item), //本月制作数（截止当天）
            monthPrice: this.getMonthPrice(data, item),  // 本月业绩（截止当天）
            monthTotalPrice: totalPrice,  // 月度总任务
            monthSuccess: this.getMonthPrice(data, item) / totalPrice, // 月度达成 = 本月业绩 / 月度总任务
            yujiPrice: (this.getMonthPrice(data, item) / this.workDay) * this.days, //预计达成金额 = 本月业绩（截止当天）/当前第几个工作日 * 本月天数
            yujiJindu: ((this.getMonthPrice(data, item) / this.workDay) * this.days) / totalPrice, // 预计月度达成
          })
          // console.log(this.dayList)
        }
      }
      // 计算总额
      let total = {
        name:'总计',
        todayNum:0,
        todayPrice: 0,
        todaySuccess: 0, // 今日达成率， 今日业绩 / 今日任务
        yesterdayNum: 0, //昨日制作数量
        yesterdayPrice: 0,  // 昨日业绩
        dayRenwu: 0, //每日任务
        yesterdaySuccess: 0, // 昨日达成率， 昨日业绩 / 每日任务
        weekNum: 0, // 本周制作数
        weekPrice: 0,  //本周业绩
        weekRenwu: 0, // 本周任务 = 每日任务 * 周工作日
        weekSuccess: 0, // 本周达成 = 本周业绩 / 本周任务
        monthNum: 0, //本月制作数（截止当天）
        monthPrice: 0,  // 本月业绩（截止当天）
        monthTotalPrice: 0,  // 月度总任务
        monthSuccess: 0, // 月度达成 = 本月业绩 / 月度总任务
        yujiPrice: 0, //预计达成金额 = 本月业绩（截止当天）/当前第几个工作日 * 本月天数
        yujiJindu: 0, // 预计月度达成
      }
      for(let item of this.dayList){
        total.todayNum += parseFloat(item['todayNum'])
        total.todayPrice += parseFloat(item['todayPrice'])
        total.todaySuccess += parseFloat(item['todaySuccess']) / this.dayList.length
        total.yesterdayNum += parseFloat(item['yesterdayNum'])
        total.yesterdayPrice += parseFloat(item['yesterdayPrice'])
        total.dayRenwu += parseFloat(item['dayRenwu'])
        total.yesterdaySuccess += parseFloat(item['yesterdaySuccess']) / this.dayList.length
        total.weekNum += parseFloat(item['weekNum'])
        total.weekPrice += parseFloat(item['weekPrice'])
        total.weekRenwu += parseFloat(item['weekRenwu'])
        total.weekSuccess += parseFloat(item['weekSuccess']) / this.dayList.length
        total.monthNum += parseFloat(item['monthNum'])
        total.monthPrice += parseFloat(item['monthPrice'])
        total.monthTotalPrice += parseFloat(item['monthTotalPrice'])
        total.monthSuccess += parseFloat(item['monthSuccess']) / this.dayList.length
        total.yujiPrice += parseFloat(item['yujiPrice'])
        total.yujiJindu += parseFloat(item['yujiJindu']) / this.dayList.length
      }
      this.dayList.push(total)

      this.loading = false
    },
    getTodayNum(data, item){
      let todayX = moment().startOf('day').format('x') // 获取当前时间戳
      // 昨天的name与时间戳都一致的数组（因为有多个产品）
      let arr = data.filter(e=>moment(e.date).startOf('day').format('x') == todayX && e.name == item.name)
      return this.arrToCount(arr, 'num')
    },
    getTodayPrice(data, item){
      let todayX = moment().startOf('day').format('x') // 获取当前时间戳
      // 昨天的name与时间戳都一致的数组（因为有多个产品）
      let arr = data.filter(e=>moment(e.date).startOf('day').format('x') == todayX && e.name == item.name)
      return this.arrToCount(arr, 'price')
    },
    getYesterdayNum(data, item){
      // let todayX = moment().startOf('day').format('x') // 获取当前时间戳
      // let yesterdayX = moment().subtract(1, 'days').startOf('day').format('x')  // 获取昨日时间戳
      let yesterdayX = this.YesterdayDate // 获取昨日时间戳
      // 昨天的name与时间戳都一致的数组（因为有多个产品）
      let arr = data.filter(e=>moment(e.date).startOf('day').format('x') == yesterdayX && e.name == item.name)
      return this.arrToCount(arr, 'num')
    },
    getYesterdayPrice(data, item){
      // let yesterdayX = moment().subtract(1, 'days').startOf('day').format('x')  // 获取昨日时间戳
      let yesterdayX = this.YesterdayDate // 获取昨日时间戳
      // 昨天的name与时间戳都一致的数组（因为有多个产品）,将每一个数组的 num 与 price相乘
      let arr = data.filter(e=>moment(e.date).startOf('day').format('x') == yesterdayX && e.name == item.name)
      return this.arrToCount(arr, 'price')
    },
    getDayRenwu(data, item){
      // totalPrice(最小值) / 每月工作日
      let totalPrice
      data.forEach(e=>{
        if(!totalPrice){totalPrice = item.totalPrice}
        if(e.name == item.name && totalPrice > e.totalPrice){
          totalPrice = e.totalPrice
        }
      })
      return parseFloat(totalPrice / this.days) 
    },
    getWeekNum(data, item){
      let todayX = moment().startOf('day').format('x') // 获取当前时间戳
      let weekStartX = moment().startOf('isoWeek').format('x') // 获取本周周一0时0分0秒
      let arr = data.filter(e=> weekStartX <= moment(e.date).startOf('day').format('x') && moment(e.date).startOf('day').format('x') <= todayX && e.name == item.name)
      return this.arrToCount(arr, 'num')
    },
    getWeekPrice(data, item){
      let todayX = moment().startOf('day').format('x') // 获取当前时间戳
      let weekStartX = moment().startOf('isoWeek').format('x') // 获取本周周一0时0分0秒
      let arr = data.filter(e=> weekStartX <= moment(e.date).startOf('day').format('x') && moment(e.date).startOf('day').format('x') <= todayX && e.name == item.name)
      return this.arrToCount(arr, 'price')
    },
    getMonthNum(data, item){
      let todayX = moment(this.end_date).format('x')
      let monthStartX = moment(this.start_date).format('x')
      let arr = data.filter(e=> monthStartX <= moment(e.date).startOf('day').format('x') && moment(e.date).startOf('day').format('x') <= todayX && e.name == item.name)
      return this.arrToCount(arr, 'num')
    },
    getMonthPrice(data, item){
      // let todayX = moment().startOf('day').format('x') // 获取当前时间戳
      // let monthStartX = moment().startOf('month').format('x') // 获取当前月第一天0时0分0秒
      let todayX = moment(this.end_date).format('x')
      let monthStartX = moment(this.start_date).format('x')
      let arr = data.filter(e=> monthStartX <= moment(e.date).startOf('day').format('x') && moment(e.date).startOf('day').format('x') <= todayX && e.name == item.name)
      return this.arrToCount(arr, 'price')
    },

    
    arrToCount(arr, key){
      // 将arr运算为各个数据,key为数量或金额, 通用，有特殊的 函数内算
      let count = 0
      if(arr.length > 0){
        for(let item of arr){
          count += parseFloat(item[key]) 
        }
        return count
      }else{
        return 0
      }
    },

    formDateChange(e){
      this.YesterdayDate = moment(e).startOf('day').format("x")
      console.log(this.YesterdayDate)
      this.getDayList()
    },
    disabledDate(current){
      return current && current > moment().endOf('day').add(-1, 'days');
    },

    async beforeUpload(file) {
      // console.log(file)
      this.loading = true
      let dataBinary = await new Promise((resolve) => {
        // Web API构造函数FileReader，可实例化对象，去调用其身上方法，去读取解析文件信息
        let reader = new FileReader(); // https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
        reader.readAsBinaryString(file)
        // console.log("实例化对象有各种方法", reader);
        reader.onload = (ev) => {
          // console.log("文件解析流程进度事件", ev);
          resolve(ev.target.result); // 将解析好的结果扔出去，以供使用
        };
      });
      
      let workBook = xlsx.read(dataBinary, {type: 'binary', cellDates: true})
      let workSheet = workBook.Sheets[workBook.SheetNames[0]]
      const data = xlsx.utils.sheet_to_json(workSheet)
      this.data = data
      console.log(data)
      this.getDayList()
      return Promise.reject();
    },
    handle_export() {
      var xlsxParam = {
        raw: true
      }; //转换成excel时，使用原始的格式，这样导出的时候数字过长不会变成科学计数法
      console.log(xlsx)
      let workbook = xlsx.utils.book_new();
      let ws1 = xlsx.utils.table_to_sheet(document.querySelector('#shumeiTable'), xlsxParam);
      xlsx.utils.book_append_sheet(workbook, ws1, '直播报表');
      let wbout = xlsx.write(workbook, {
          bookType: 'xlsx',
          bookSST: true,
          type: 'array'
      });
      try {
          FileSaver.saveAs(
          new Blob([wbout], {
              type: 'application/octet-stream;charset=utf-8"'
          }), '数媒报表.xlsx');
      } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout);
      }
      return wbout;
    },
    formDateChange2(e){
      this.start_date = e[0].format("YYYY-MM-DD")
      this.end_date = e[1].format("YYYY-MM-DD")
      this.createData()
    },
    disabledDate2(current){
      return current && current > moment().endOf('day');
    },
  }
}
</script>

<style lang="less" scoped>

</style>
